
const languageService = function($translate, $rootScope) {
  'ngInject';

  const vm = this;

  // 支持的语言列表
  vm.supportedLanguages = [
    { 
      code: 'zh', 
      name: '中文简体',
      nameEn: 'Chinese Simplified',
      flag: '🇨🇳' 
    },
    { 
      code: 'en', 
      name: 'English',
      nameEn: 'English', 
      flag: '🇺🇸' 
    }
  ];

  // 当前语言
  vm.currentLanguage = 'zh';

  /**
   * 初始化语言设置
   */
  vm.init = function() {
    // 从本地存储获取语言设置，如果没有则使用默认语言
    const savedLanguage = localStorage.getItem('language') || 'zh';
    vm.changeLanguage(savedLanguage);
  };

  /**
   * 获取当前语言
   */
  vm.getCurrentLanguage = function() {
    return vm.currentLanguage;
  };

  /**
   * 获取当前语言信息对象
   */
  vm.getCurrentLanguageInfo = function() {
    return vm.supportedLanguages.find(lang => lang.code === vm.currentLanguage);
  };

  /**
   * 获取支持的语言列表
   */
  vm.getSupportedLanguages = function() {
    return vm.supportedLanguages;
  };

  /**
   * 切换语言
   */
  vm.changeLanguage = function(languageCode) {
    if (!languageCode || !vm.isLanguageSupported(languageCode)) {
      console.warn('不支持的语言代码:', languageCode);
      return;
    }

    // 使用 angular-translate 切换语言
    $translate.use(languageCode).then(() => {
      vm.currentLanguage = languageCode;
      
      // 保存到本地存储
      localStorage.setItem('language', languageCode);
      
      // 触发语言变更事件
      $rootScope.$broadcast('languageChanged', {
        oldLanguage: vm.currentLanguage,
        newLanguage: languageCode,
        languageInfo: vm.getCurrentLanguageInfo()
      });

      console.log('语言已切换到:', languageCode);
    }).catch(error => {
      console.error('语言切换失败:', error);
    });
  };

  /**
   * 检查是否支持指定语言
   */
  vm.isLanguageSupported = function(languageCode) {
    return vm.supportedLanguages.some(lang => lang.code === languageCode);
  };

  /**
   * 获取语言名称
   */
  vm.getLanguageName = function(languageCode, currentLang) {
    const lang = vm.supportedLanguages.find(l => l.code === languageCode);
    if (!lang) return languageCode;
    
    // 根据当前语言返回对应的语言名称
    return currentLang === 'en' ? lang.nameEn : lang.name;
  };

  /**
   * 获取下一个语言（用于快速切换）
   */
  vm.getNextLanguage = function() {
    const currentIndex = vm.supportedLanguages.findIndex(lang => lang.code === vm.currentLanguage);
    const nextIndex = (currentIndex + 1) % vm.supportedLanguages.length;
    return vm.supportedLanguages[nextIndex].code;
  };

  /**
   * 切换到下一个语言
   */
  vm.switchToNext = function() {
    const nextLanguage = vm.getNextLanguage();
    vm.changeLanguage(nextLanguage);
  };

  /**
   * 根据浏览器语言自动设置
   */
  vm.setLanguageFromBrowser = function() {
    const browserLanguage = navigator.language || navigator.languages[0];
    let targetLanguage = 'zh'; // 默认中文

    // 简单的语言匹配
    if (browserLanguage.startsWith('en')) {
      targetLanguage = 'en';
    } else if (browserLanguage.startsWith('zh')) {
      targetLanguage = 'zh';
    }

    vm.changeLanguage(targetLanguage);
  };

  // 监听翻译变更事件
  $rootScope.$on('$translateChangeSuccess', function(event, data) {
    vm.currentLanguage = data.language;
  });

  // 初始化
  vm.init();

  return vm;
};

function initLanguageService() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化语言服务模块');
    return;
  }

  angular.module('app.services.language', [])
    .service('LanguageService', languageService);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initLanguageService();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initLanguageService();
}